<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 2015/7/1
 * Time: 17:25
 */
namespace Admin\Controller;
use Think\Controller;
use User\Api\UserApi;
use Api\Department\DepartmentApi;
class JiangSuController extends  AdminController{
    public function index(){
        $Unit = M('Department_15');
        $order = 'convert(name using gb2312) asc';
        $list = $this->lists($Unit,array(),$order);
        $this->assign('_list', $list);
        $this->meta_title = '机构管理';
        $this->display();
    }

    /*
     * 机构编辑
     */
    public function edit(){
        if(IS_POST){
            $data = I('post.');
            $Department =M('Department_15');
            $data['name'] = getAgencynameById($data['fid']);
            $departmentId = $Department->save($data);
            if($departmentId>0){
                $this->Jiang_catch(1);
				
                $this->success('修改成功',U('JiangSu/index'));
            }else{
                $this->error($this->showRegError($departmentId));
            }
        }else{
            $id = I('get.id');
            $type = I('type');
            $Department = M('Department_15');
            $info = $Department->find($id);
            $this->getCategory();
            //显示图片
            $upload_ids_arr = explode(',',$info['img']);
            $this->assign('upload_ids_arr',$upload_ids_arr);
            //得到所有的查新机构
            $arr =M('Department_15')->getField('id,fid');
            $id_a =  count($arr) > 0?join(',',$arr):0;
            $list = M('Department')->where("id not in ($id_a)")->select();
            $this->assign('list',$list);
            $this->assign('info', $info);
            $this->assign('type', $type);
            $this->meta_title = '机构编辑';
            $this->display();
        }
    }

    /*
     * 添加机构
     */
    public function add(){
        if(IS_POST){
            $data = I('post.');
//            $data = D('Department_15')->create();
            $data['name'] = getAgencynameById($data['fid']);
            $departmentId = M('Department_15')->add($data);
            $data['id'] = $departmentId;
            if(0<$departmentId){
                $this->Jiang_catch(1);
                $this->success('添加成功',U('JiangSu/index'));
            }else{
                $this->error($this->showRegError($departmentId));
            }
        }else{
            $this->getCategory();
            //得到所有的查新机构
            $arr =M('Department_15')->getField('id,fid');
            $id_a =  count($arr) > 0?join(',',$arr):0;
            $list = M('Department')->where("id not in ($id_a)")->select();
            $this->assign('list',$list);
            $this->meta_title = '机构新增';
            $this->display('edit');
        }
    }

//    删除机构
    public  function  del()
    {
        $id = I('id');
        $Department = M('Department_15');
        $info = $Department->find($id);
        if($info)
        {
            if($Department->delete($id))
            {
                $this->Jiang_catch(1);
                $this->success('删除成功',U('index'));
            }
            else
            {
                $this->error('删除失败！');
            }
        }
        else
        {
            $this->error('该条数据不存在！');
        }
    }


    private function showRegError($code = 0){
        switch ($code) {
            case -1:  $error = '账号长度必须在16个字符以内！'; break;
            case -2:  $error = '账号被占用！'; break;
            case -3:  $error = '机构名称被占用！'; break;
            case -4:  $error = '密码长度必须在6-30个字符之间！'; break;
            case -5:  $error = '邮箱格式不正确！'; break;
            case -6:  $error = '邮箱长度必须在1-32个字符之间！'; break;
            case -7:  $error = '邮箱被禁止注册！'; break;
            case -8:  $error = '邮箱被占用！'; break;
            case -9:  $error = '手机格式不正确！'; break;
            case -10: $error = '手机被禁止注册！'; break;
            case -11: $error = '手机号被占用！'; break;
            case -12: $error = '机构名称必须在1-255个字符之间！'; break;
            case -119: $error = '添加用户出错';break;
            case -13: $error = '通讯地址必须在1-255个字符之间！';break;
            case -14: $error = '请选择挂靠单位！';break;
            case -15: $error = '请选择查新范围！';break;
            default:  $error = '未知错误';
        }
        return $error;
    }
    private function Jiang_catch($tag=''){
        if(empty($tag))		//读取缓存
        {
            return S('Jiang_catch');
        }
        else				//写入缓存
        {
            S('Jiang_catch',null);
            $order = 'convert(name using gb2312) asc';
            $model = M('Department_15');
            $list  = $model->order($order)->getField('id,id,fid,name,city,url,content,img');
            S('Jiang_catch',$list);
            return true;
        }
    }
    //获取所有的查新范围
    private function getCategory(){
        $list = M('school_type')->where('status=1')->select();
        $this->assign('category',$list);
    }

    public function upload(){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $tmp_can	=	$_GET['can']?$_GET['can']:0;
        if($tmp_can==1){
            $upload->exts      =     array('jpg','png','jpeg','gif','bmp');// 设置附件上传类型
        }else{
            $upload->exts      =     array('doc', 'rar','zip','docx');// 设置附件上传类型
        }
        $upload->rootPath  =     './uploads/school/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        $tmp_name	=	$_GET['tmp_name'];

        // 上传文件
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            echo json_encode(array('state'=>$upload->getError()));
        }else{// 上传成功
            //print_R($info);exit;
            $file=array(
                'uid'=>UID,
                'title'=>$info[$tmp_name]['name'],
                'title_r'=>$info[$tmp_name]['savename'],
                'type'=>'1',
                'size'=>$info[$tmp_name]['size'],
                'dir'=>$upload->rootPath.$info[$tmp_name]['savepath'],
                'create_time'=>date('Y-m-d h:i:s')
            );
            $id = M('Attachment')->add($file);
            echo json_encode(array('state'=>'ok','upload_id'=>$id,'base_file_n'=>$file['title']));
        }
    }

    public function down_file(){
        $file_id=$_GET['file_id'];
        if(empty($file_id)){
            redirect("文件不存在跳转页面");
        }else{//如果要加登录条件，这里可以自己加
            $map['id'] = $file_id;
            $list=D('Attachment')->where($map)->select();
            if ($list == false) {//文件不存在，可以跳转到其它页面
                header('HTTP/1.0 404 Not Found');
                header('Location: .');
            } else {
                $file_name="./".$list[0]['dir'].$list[0]['title_r'];//需要下载的文件
                $file_name=iconv("utf-8","gb2312","$file_name");
                if(file_exists($file_name)){
                    $fp=@fopen($file_name,"r+");//下载文件必须先要将文件打开，写入内存
                    if(!file_exists($file_name)){//判断文件是否存在
                        $this->error('文件不存在！');
                    }
                    $file_size=filesize($file_name);//判断文件大小
                    //返回的文件
                    Header("Content-type: application/octet-stream");
                    //按照字节格式返回
                    Header("Accept-Ranges: bytes");
                    //返回文件大小
                    Header("Accept-Length: ".$file_size);
                    //弹出客户端对话框，对应的文件名
                    Header("Content-Disposition: attachment; filename=".$list[0]['title']);
                    //防止<span id="2_nwp" style="width: auto; height: auto; float: none;"><a id="2_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?c=news&cf=1001&ch=0&di=128&fv=16&jk=208efa6f3933ab0f&k=%B7%FE%CE%F1%C6%F7&k0=%B7%FE%CE%F1%C6%F7&kdi0=0&luki=3&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=fab33396ffa8e20&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F971%2Ehtml&urlid=0" target="_blank" mpid="2" style="text-decoration: none;"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">服务器</span></a></span>瞬时压力增大，分段读取
                    $buffer=1024;
                    while(!feof($fp)){
                        $file_data=fread($fp,$buffer);
                        echo $file_data;
                    }
                    //关闭文件
                    fclose($fp);
                }else{
                    $this->error('文件不存在！');
                }

            }
        }
    }
}